<template>
  <base-layout simple>
    <article class="base-layout__inner column">
      <!-- 查询条件 -->
      <t-form
        ref="form"
        :data="queryParams"
        label-width="80px"
        layout="inline"
        class="search-form"
        colon
      >
        <t-row style="width: 100%">
          <t-col :span="3">
            <t-form-item label="菜单名称">
              <t-input
                v-model="queryParams.name"
                placeholder="请输入菜单名称"
                clearable
                style="width: 158px"
              />
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item label="路由地址">
              <t-input
                v-model="queryParams.path"
                placeholder="请输入路由地址"
                clearable
                style="width: 158px"
              />
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item label="菜单类型">
              <t-select
                v-model="queryParams.type"
                placeholder="请选择菜单类型"
                clearable
                style="width: 158px"
              >
                <t-option :value="0" label="目录" />
                <t-option :value="1" label="菜单" />
                <t-option :value="2" label="权限" />
              </t-select>
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item>
              <t-space>
                <t-button theme="primary" @click="handleSearch">查询</t-button>
                <t-button theme="default" @click="handleReset">重置</t-button>
              </t-space>
            </t-form-item>
          </t-col>
        </t-row>

        <t-row style="width: 100%">
          <t-col :span="3">
            <t-row>
              <t-space>
                <t-button theme="primary" @click="handleAdd">新增菜单</t-button>
                <t-button theme="default" @click="onExpandAllToggle">
                  {{ expandAll ? '收起全部' : '展开全部' }}
                </t-button>
              </t-space>
            </t-row>
          </t-col>
          <t-col :span="9"></t-col>
        </t-row>
      </t-form>

      <!-- 树形表格 -->
      <t-enhanced-table
        ref="table"
        row-key="id"
        :data="menuData"
        :columns="columns"
        :tree="{
          childrenKey: 'children',
          treeNodeColumnIndex: 0,
          expandTreeNodeOnClick: false,
          indent: 44,
        }"
        :expanded-tree-nodes.sync="expandedTreeNodes"
        :loading="loading"
        bordered
        size="small"
        height="calc(100vh - 250px)"
      />
    </article>

    <!-- 菜单编辑器抽屉 -->
    <menu-form-drawer
      :visible.sync="editorVisible"
      :is-edit="isEdit"
      :current-edit-data="currentEditData"
      :flat-menu-options="flatMenuOptions"
      @save="handleSave"
      @close="handleCloseEditor"
      ref="menuFormDrawer"
    />
  </base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import MenuFormDrawer from './MenuDrawer.vue';
import {
  Button as TButton,
  Tag as TTag,
  EnhancedTable,
  Icon as TIcon,
  Popconfirm as TPopconfirm,
} from 'tdesign-vue';
import { getMenuList, createMenu, updateMenu, deleteMenu } from '@/api/menu';

export default {
  name: 'SystemMenus',
  components: {
    BaseLayout,
    MenuFormDrawer,
    TEnhancedTable: EnhancedTable,
    TButton,
  },
  data() {
    return {
      loading: false,
      expandAll: true,
      expandedTreeNodes: [],
      editorVisible: false,
      currentEditData: null,
      isEdit: false,

      // 类型选项映射
      typeMap: {
        0: { label: '目录', theme: 'primary', variant: 'light-outline' },
        1: { label: '菜单', theme: 'success', variant: 'dark' },
        2: { label: '权限', theme: 'warning', variant: 'light' },
      },

      // 查询参数
      queryParams: {
        name: '',
        path: '',
        type: '',
      },

      // 表格列配置
      columns: [
        {
          colKey: 'name',
          title: '菜单名称',
          width: 200,
          ellipsis: true,
          cell: (h, { row }) => {
            return row.name || row.nodeName || '-';
          },
        },
				{
          colKey: 'icon',
          title: '图标',
          width: 80,
          align: 'center',
          cell: (h, { row }) => {
            const icon = row.icon;
            if (icon) {
              return h(TIcon, {
                props: { name: icon },
                style: { fontSize: '18px' }
              });
            }
            return h('span', { style: { color: '#ddd' } }, '-');
          },
        },
        {
          colKey: 'type',
          title: '菜单类型',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const type =
              row.type !== undefined ? row.type : this.convertMenuTypeToType(row.menuType);
            const typeInfo = this.typeMap[type] || { label: '未知', theme: 'default', variant: 'light' };
            return h(
              TTag,
              {
                props: {
                  theme: typeInfo.theme,
                  size: 'small',
                  variant: typeInfo.variant,
                },
              },
              typeInfo.label
            );
          },
        },
        {
          colKey: 'path',
          title: '路由地址',
          width: 200,
          ellipsis: true,
          cell: (h, { row }) => {
            return row.path || row.routePath || row.route || '-';
          },
        },
        {
          colKey: 'component',
          title: '组件地址',
					width: 180,
          ellipsis: true,
          cell: (h, { row }) => {
            return row.component || row.filePath || '-';
          },
        },
				{
          colKey: 'permission',
          title: '权限标识',
          width: 180,
          ellipsis: true,
          cell: (h, { row }) => {
            const permission = row.permission || '';
            if (!permission) {
              return h('span', { style: { color: '#999' } }, '-');
            }
            return h(
              TTag,
              {
                props: {
                  theme: 'primary',
                  variant: 'light',
                  size: 'small',
                },
                style: {
                  fontFamily: 'Monaco, Consolas, monospace',
                  fontSize: '12px',
                },
              },
              permission
            );
          },
        },
        {
          colKey: 'orderNo',
          title: '排序号',
          width: 80,
          align: 'center',
          cell: (h, { row }) => {
            return h(
              'span',
              {},
              row.orderNo !== undefined
                ? row.orderNo
                : row.sortOrder !== undefined
                ? row.sortOrder
                : row.sort || 0
            );
          },
        },
        {
          colKey: 'status',
          title: '状态',
          width: 80,
          align: 'center',
          cell: (h, { row }) => {
            return h(
              TTag,
              {
                props: {
                  theme: row.status === 1 ? 'success' : 'danger',
                  size: 'small',
                  variant: 'light',
                },
              },
              row.status === 1 ? '启用' : '禁用'
            );
          },
        },
        {
          colKey: 'operate',
          title: '操作',
          width: 140,
          fixed: 'right',
          cell: (h, { row }) => {
            const hasChildren = this.checkHasChildren(row.id);

            return h('div', { class: 'table-operations' }, [
              h(
                'TButton',
                {
                  props: {
                    variant: 'text',
                    theme: 'primary',
                    size: 'small',
                  },
                  on: {
                    click: () => this.handleEdit(row),
                  },
                },
                '编辑'
              ),
              h(
                TPopconfirm,
                {
                  props: {
                    content: hasChildren
                      ? '该菜单下存在子菜单，无法删除！'
                      : '确认删除吗？删除后不可恢复！',
                    disabled: hasChildren,
                  },
                  on: hasChildren ? {} : {
                    confirm: () => this.handleDelete(row),
                  },
                },
                [
                  h(
                    'TButton',
                    {
                      props: {
                        variant: 'text',
                        theme: hasChildren ? 'default' : 'danger',
                        size: 'small',
                        disabled: hasChildren,
                        title: hasChildren ? '该菜单下存在子菜单，无法删除' : '删除菜单',
                      },
                    },
                    '删除'
                  ),
                ]
              ),
            ]);
          },
        },
      ],

      // 菜单数据
      menuData: [],
      // 原始菜单数据（用于过滤）
      originalMenuData: [],
    };
  },

  computed: {
    // 扁平化的菜单选项，用于父级菜单选择
    flatMenuOptions() {
      const flatten = (menus, level = 0) => {
        const result = [];
        menus.forEach((menu) => {
          const prefix = '　'.repeat(level);
          result.push({
            id: menu.id,
            label: `${prefix}${menu.name || menu.nodeName}`,
          });
          if (menu.children && menu.children.length > 0) {
            result.push(...flatten(menu.children, level + 1));
          }
        });
        return result;
      };
      return flatten(this.originalMenuData);
    },
  },

  mounted() {
    this.getMenuList();
  },

  methods: {
    // 获取菜单列表
    async getMenuList() {
      this.loading = true;
      try {
        // 过滤掉空值参数
        const params = this.filterEmptyParams(this.queryParams);
        const response = await getMenuList(params);

        // 处理响应数据
        if (response.data && response.data.code === 200) {
          this.originalMenuData = response.data.data || [];
          this.menuData = this.filterMenuData(this.originalMenuData);
        } else {
          // 如果后端还未实现，暂时使用模拟数据
          console.warn('菜单API未实现，使用模拟数据');
          this.originalMenuData = this.getMockData();
          this.menuData = this.filterMenuData(this.originalMenuData);
        }

        // 展开所有节点
        this.$nextTick(() => {
          if (this.$refs.table && this.menuData.length > 0) {
            this.expandedTreeNodes = [];
            setTimeout(() => {
              if (this.$refs.table) {
                this.$refs.table.expandAll();
              }
            }, 100);
          }
        });
      } catch (error) {
        console.error('获取菜单列表失败:', error);
        // 出错时使用模拟数据
        this.originalMenuData = this.getMockData();
        this.menuData = this.filterMenuData(this.originalMenuData);
        this.$message.error('获取菜单列表失败，使用模拟数据');
      } finally {
        this.loading = false;
      }
    },

    // 过滤空值参数
    filterEmptyParams(params) {
      const filteredParams = {};
      for (const key in params) {
        if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
          filteredParams[key] = params[key];
        }
      }
      return filteredParams;
    },

    // 模拟数据（用于后端未实现时的fallback）
    getMockData() {
      return [
        {
          id: 1,
          name: '系统管理',
          type: 0, // 目录
          path: '/system',
          orderNo: 1,
          status: 1,
          parentId: null,
          isExt: false,
          show: 1,
          createdAt: '2024-01-01 10:00:00',
          // 保持原有字段以确保向后兼容
          nodeName: '系统管理',
          menuType: 1,
          routePath: '/system',
          sortOrder: 1,
          isVisible: 1,
          route: '/system',
          filePath: '',
          permission: '',
          icon: 'setting',
          sort: 1,
          remark: '系统管理模块',
          children: [
            {
              id: 2,
              name: '用户管理',
              type: 1, // 菜单
              path: '/system/user',
              orderNo: 1,
              status: 1,
              parentId: 1,
              isExt: false,
              show: 1,
              createdAt: '2024-01-01 10:05:00',
              // 保持原有字段
              nodeName: '用户管理',
              menuType: 2,
              routePath: '/system/user',
              sortOrder: 1,
              isVisible: 1,
              route: '/system/user',
              filePath: '@/views/system/user/index.vue',
              permission: 'system:user:view',
              icon: 'user',
              sort: 1,
              remark: '用户管理功能',
              children: [
                {
                  id: 6,
                  name: '新增用户',
                  type: 2, // 权限
                  path: '',
                  orderNo: 1,
                  status: 1,
                  parentId: 2,
                  isExt: false,
                  show: 1,
                  createdAt: '2024-01-01 10:06:00',
                  // 保持原有字段
                  nodeName: '新增用户',
                  menuType: 3,
                  routePath: '',
                  sortOrder: 1,
                  isVisible: 1,
                  route: '',
                  filePath: '',
                  permission: 'system:user:add',
                  icon: '',
                  sort: 1,
                  remark: '新增用户权限',
                  children: [],
                },
                {
                  id: 7,
                  name: '编辑用户',
                  type: 2, // 权限
                  path: '',
                  orderNo: 2,
                  status: 1,
                  parentId: 2,
                  isExt: false,
                  show: 1,
                  createdAt: '2024-01-01 10:07:00',
                  // 保持原有字段
                  nodeName: '编辑用户',
                  menuType: 3,
                  routePath: '',
                  sortOrder: 2,
                  isVisible: 1,
                  route: '',
                  filePath: '',
                  permission: 'system:user:edit',
                  icon: '',
                  sort: 2,
                  remark: '编辑用户权限',
                  children: [],
                },
              ],
            },
            {
              id: 3,
              name: '菜单管理',
              type: 1, // 菜单
              path: '/system/menus',
              orderNo: 2,
              status: 1,
              parentId: 1,
              isExt: false,
              show: 1,
              createdAt: '2024-01-01 10:10:00',
              // 保持原有字段
              nodeName: '菜单管理',
              menuType: 2,
              routePath: '/system/menus',
              sortOrder: 2,
              isVisible: 1,
              route: '/system/menus',
              filePath: '@/views/system/menus/index.vue',
              permission: 'system:menu:view',
              icon: 'menu-fold',
              sort: 2,
              remark: '菜单管理功能',
              children: [],
            },
          ],
        },
        {
          id: 4,
          name: '运营管理',
          type: 0, // 目录
          path: '/operation',
          orderNo: 2,
          status: 1,
          parentId: null,
          isExt: false,
          show: 1,
          createdAt: '2024-01-01 11:00:00',
          // 保持原有字段
          nodeName: '运营管理',
          menuType: 1,
          routePath: '/operation',
          sortOrder: 2,
          isVisible: 1,
          route: '/operation',
          filePath: '',
          permission: '',
          icon: 'tools',
          sort: 2,
          remark: '运营管理模块',
          children: [
            {
              id: 5,
              name: '疾病管理',
              type: 1, // 菜单
              path: '/operation/disease',
              orderNo: 1,
              status: 1,
              parentId: 4,
              isExt: false,
              show: 1,
              createdAt: '2024-01-01 11:05:00',
              // 保持原有字段
              nodeName: '疾病管理',
              menuType: 2,
              routePath: '/operation/disease',
              sortOrder: 1,
              isVisible: 1,
              route: '/operation/disease',
              filePath: '@/views/operation/disease/index.vue',
              permission: 'operation:disease:view',
              icon: 'heart',
              sort: 1,
              remark: '疾病管理功能',
              children: [],
            },
          ],
        },
      ];
    },

    // 过滤菜单数据
    filterMenuData(data) {
      const { name, path, type } = this.queryParams;

      // 如果没有任何查询条件，直接返回原数据
      if (!name && !path && !type) {
        return data;
      }

      const filterTree = (nodes) => {
        return nodes.filter((node) => {
          // 菜单名称过滤
          const nameMatch =
            !name ||
            (node.name && node.name.includes(name)) ||
            (node.nodeName && node.nodeName.includes(name));
          // 路由地址过滤
          const routeMatch =
            !path ||
            (node.path && node.path.includes(path)) ||
            (node.routePath && node.routePath.includes(path)) ||
            (node.route && node.route.includes(path));
          // 菜单类型过滤
          const typeMatch =
            !type ||
            node.type === parseInt(type) ||
            this.convertMenuTypeToType(node.menuType) === parseInt(type);

          // 过滤子节点
          if (node.children && node.children.length > 0) {
            node.children = filterTree(node.children);
          }

          // 如果当前节点匹配或者有子节点匹配，则保留
          return (
            (nameMatch && routeMatch && typeMatch) || (node.children && node.children.length > 0)
          );
        });
      };

      return filterTree(JSON.parse(JSON.stringify(data)));
    },

    // 查询
    handleSearch() {
      this.getMenuList();
    },

    // 重置查询条件
    handleReset() {
      this.queryParams = {
        name: '',
        path: '',
        type: '',
      };
      this.getMenuList();
    },

    // 展开/收起全部
    onExpandAllToggle() {
      this.expandAll = !this.expandAll;
      this.expandAll ? this.$refs.table.expandAll() : this.$refs.table.foldAll();
    },

    // 新增菜单
    handleAdd() {
      this.isEdit = false;
      this.currentEditData = null;
      this.editorVisible = true;
    },

    // 编辑菜单
    handleEdit(row) {
      this.isEdit = true;
      // 复制数据并确保type字段正确
      this.currentEditData = { ...row };

      // 如果没有type字段但有menuType字段，进行转换
      if (this.currentEditData.type === undefined && this.currentEditData.menuType !== undefined) {
        this.currentEditData.type = this.convertMenuTypeToType(this.currentEditData.menuType);
      }

      // 确保type字段存在，如果都没有则默认为菜单类型
      if (this.currentEditData.type === undefined) {
        this.currentEditData.type = 1; // 默认为菜单
      }

      this.editorVisible = true;
    },

    // 保存菜单
    async handleSave(formData) {
      try {
        // 设置抽屉的保存loading状态
        if (this.$refs.menuFormDrawer) {
          this.$refs.menuFormDrawer.setSaveLoading(true);
        }

        let response;
        if (this.isEdit) {
          // 更新菜单
          response = await updateMenu(this.currentEditData.id, formData);
        } else {
          // 新增菜单
          response = await createMenu(formData);
        }

        if (response.data && response.data.code === 200) {
          this.$message.success(this.isEdit ? '菜单更新成功' : '菜单创建成功');
          this.editorVisible = false;
          this.getMenuList();
        } else {
          throw new Error(response.data?.message || '操作失败');
        }
      } catch (error) {
        console.error('保存菜单失败:', error);
        // 如果是API未实现的错误，给出提示但不阻止操作
        if (error.response?.status === 404) {
          this.$message.warning('菜单API未实现，请先实现后端接口');
        } else {
          this.$message.error('保存菜单失败: ' + (error.message || '未知错误'));
        }
      } finally {
        if (this.$refs.menuFormDrawer) {
          this.$refs.menuFormDrawer.setSaveLoading(false);
        }
      }
    },

    // 删除菜单
    async handleDelete(row) {
      try {
        // 更严格地检查是否有子菜单
        const hasChildren = this.checkHasChildren(row.id);
        if (hasChildren) {
          this.$message.warning({
            content: `该菜单下存在子菜单，请先删除子菜单后再删除该菜单！`,
            duration: 3000,
          });
          return;
        }

        const response = await deleteMenu(row.id);

        if (response.data && response.data.code === 200) {
          this.$message.success('菜单删除成功');
          this.getMenuList();
        } else {
          throw new Error(response.data?.message || '删除失败');
        }
      } catch (error) {
        console.error('删除菜单失败:', error);
        // 如果是API未实现的错误，给出提示但不阻止操作
        if (error.response?.status === 404) {
          this.$message.warning('菜单API未实现，请先实现后端接口');
        } else {
          this.$message.error('删除菜单失败: ' + (error.message || '未知错误'));
        }
      }
    },

    // 检查菜单是否有子菜单
    checkHasChildren(menuId) {
      // 递归检查原始数据中是否存在以该菜单为父级的子菜单
      const checkInData = (data) => {
        for (const item of data) {
          // 检查直接子菜单
          if (item.parentId === menuId) {
            return true;
          }
          // 检查children属性
          if (item.children && item.children.length > 0) {
            for (const child of item.children) {
              if (child.parentId === menuId) {
                return true;
              }
            }
            // 递归检查子菜单的子菜单
            if (checkInData(item.children)) {
              return true;
            }
          }
        }
        return false;
      };

      // 检查原始数据
      if (this.originalMenuData && this.originalMenuData.length > 0) {
        return checkInData(this.originalMenuData);
      }

      // 如果没有原始数据，检查当前显示的数据
      if (this.menuData && this.menuData.length > 0) {
        return checkInData(this.menuData);
      }

      return false;
    },

    // 关闭编辑器
    handleCloseEditor() {
      this.editorVisible = false;
      this.currentEditData = null;
      // 清除保存状态
      if (this.$refs.menuFormDrawer) {
        this.$refs.menuFormDrawer.setSaveLoading(false);
      }
    },

    // 转换菜单类型为类型
    convertMenuTypeToType(menuType) {
      // 前端原有的menuType: 1-目录, 2-菜单, 3-权限
      // 服务端的type: 0-目录, 1-菜单, 2-权限
      switch (menuType) {
        case 1:
          return 0; // 目录
        case 2:
          return 1; // 菜单
        case 3:
          return 2; // 权限
        default:
          return 0;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.search-form {
  background: #fff;
}

/deep/ .table-operations {
  .t-button {
    margin-right: 8px;
  }
}

/deep/ .t-enhanced-table {
  .t-table__header {
    background-color: #f5f7fa;
  }
}
</style>
